
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import org.xml.sax.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author frke0900
 */
public class Customer {
    DocumentBuilderFactory fac;
    DocumentBuilder build;;

    int budget = 5000;
    int itemsBought = 0;
    int month;

    Customer() {
        try {
            fac = DocumentBuilderFactory.newInstance();
            build = fac.newDocumentBuilder();
        } catch (Exception e) {
            System.err.println("Error: "+e.getMessage());
            System.exit(1);
        }
        month = parseMonth();
        buyMandatoryItems();
        buyTrendItems();
        waitForNewMonth();
    }

    private void waitForNewMonth() {
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                int newMonth = parseMonth();
                if (month != newMonth) {
                    month = newMonth;
                    budget += 5000;
                    itemsBought = 0;
                    
                    buyMandatoryItems();
                    buyTrendItems();
                }
            }
        };
        timer.schedule(task, 3000, 3000);
        
    }

    private int parseMonth() {
        String xml = getMonth();
        try {
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            Document doc = build.parse(is);

            Element root = doc.getDocumentElement();
            System.out.println(xml);
            return Integer.parseInt(root.getFirstChild().getTextContent());


        }
        catch(Throwable t) {
            System.err.println("parseMonth error: "+t.getMessage());
            t.printStackTrace();
            return -1;
        }
    }

    private void buyMandatoryItems() {
        String buyXML = "<order><id>3</id><quantity>9001</quantity></order>";
    }

    private void buyTrendItems() {
        Random rand = new Random();
        String xml = getAllItems();
        List<Item> items = parseItems(xml);
        
        int trys =0;
        while(budget>1000 && itemsBought < 5) {
            trys++;
            int randomInt = rand.nextInt(items.size());
            if(items.get(randomInt).getPrice()<budget) {
                orderItem(items.get(randomInt));
                itemsBought++;
                budget-=items.get(randomInt).getPrice();
                System.out.println(budget);
            }

            if(trys>20)
                break;
        }
    }

    private void orderItem(Item item) {
        Document doc = build.newDocument();
        
        Element root = doc.createElement("order");
        doc.appendChild(root);

        Element id = doc.createElement("id");
        root.appendChild(id);
        id.appendChild(doc.createTextNode(""+item.getId()));

        Element quantity = doc.createElement("quantity");
        root.appendChild(quantity);
        quantity.appendChild(doc.createTextNode("1"));

        String result = buyItem(xmlToString(doc));
        System.out.println(result);
    }

    private List parseItems(String xml) {
        System.out.println("parse: "+xml);
        ArrayList<Item> items = new ArrayList<Item>();
        try {
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));         
            Document doc = build.parse(is);

            Element root = doc.getDocumentElement();
            NodeList nl = root.getElementsByTagName("item");
            if(nl!=null && nl.getLength()>0) {
                for(int i=0;i<nl.getLength();i++){
                    Element currentNode = (Element)nl.item(i);
                    int id = Integer.parseInt(currentNode.getElementsByTagName("id").item(0).getTextContent());
                    int price = Integer.parseInt(currentNode.getElementsByTagName("price").item(0).getTextContent());
                    int quantity = Integer.parseInt(currentNode.getElementsByTagName("quantity").item(0).getTextContent());
                    String name = currentNode.getElementsByTagName("name").item(0).getTextContent();

                    items.add(new Item(id, price, quantity, name));
                }
            }

        } catch(Exception e) {
            System.err.println("error");
        }
        return items;
    }

    private String xmlToString(Document doc) {
        try {
            StringWriter buffer = new StringWriter();
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            transformer.transform(new DOMSource(doc), new StreamResult(buffer));
            return buffer.toString();
        } catch (Throwable t) {
            return "ERROR: " + t.getMessage();
        }
    }

    public static void main(String[] args) {
        new Customer();
    }

    private static String getAllItems() {
        warehouse.WarehouseService service = new warehouse.WarehouseService();
        warehouse.Warehouse port = service.getWarehousePort();
        return port.getAllItems();
    }

    private static String buyItem(java.lang.String order) {
        warehouse.WarehouseService service = new warehouse.WarehouseService();
        warehouse.Warehouse port = service.getWarehousePort();
        return port.buyItem(order);
    }

    private static String getMonth() {
        warehouse.WarehouseService service = new warehouse.WarehouseService();
        warehouse.Warehouse port = service.getWarehousePort();
        return port.getMonth();
    }

}
